package com.gitee.magic.framework.head.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.converter.DocDescription;
import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.utils.codec.Base64;

/**
 * @author start
 */
@DocDescription("Baes64序列化")
public class SerializeConverterEditor extends AbstractConverterEditor<Object>  {
	
	public SerializeConverterEditor(Class<?> prototype) {
		super(prototype);
	}
	
	@Override
	public void restore(Object value) {
		if(value!=null) {
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			try(ObjectOutputStream oos=new ObjectOutputStream(bos)){
				oos.writeObject(value);
			} catch (IOException e) {
				throw new ApplicationException(e);
			}
			setValue(Base64.encode(bos.toByteArray()));
		}
	}

	@Override
	public Object converter() {
		if(getValue()==null) {
			return null;
		}
		byte[] buf=Base64.decode(String.valueOf(getValue()));
		ByteArrayInputStream bos=new ByteArrayInputStream(buf);
		try(ObjectInputStream oos=new ObjectInputStream(bos)){
			return oos.readObject();
		} catch (ClassNotFoundException | IOException e) {
			throw new ApplicationException(e);
		}
	}
	
}
